package com.rd.student.jiaji.class3.wangyanbo.task24;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestThreadPool {
    public static void main(String[] args) {
        cachedPool();
        fixedPool();
        scheduledPool();
        scheduledPool1();
        singleExecutor();

    }
    public static void cachedPool(){
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        for (int i=0;i<10;i++){
            cachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
    }
    public static void fixedPool(){
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
        for (int i=0;i<10;i++){
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }


    }
public static void scheduledPool(){
    ScheduledExecutorService scheduledThreadPool=
            Executors.newScheduledThreadPool(5);
    scheduledThreadPool.schedule(new Runnable(){
        @Override
        public  void run(){
            System.out.println("延时执行");
        }
    },2, TimeUnit.SECONDS);
}
public static void scheduledPool1(){
    ScheduledExecutorService scheduledThreadPool =
            Executors.newScheduledThreadPool(5);
    scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            System.out.println("定时执行");
        }
    }, 1, 2, TimeUnit.SECONDS);
}
public static void singleExecutor(){
        ExecutorService singleExecutor=Executors.newSingleThreadExecutor();

        for (int i=0;i<10;i++){
            singleExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try{
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
}

}
